<template>
	
	<view class="left clearfix bai">
		<uni-popup ref="popup" type="center">
			<view class="mate-box left clearfix">
				<view class="mate-title-box left clearfix">
					<view class="mate-title-left left">
						<label v-if="folerItem && folerItem._id" @click="folerItem = null">
							<uni-icons type="left" size="15" color="#666"></uni-icons>
						</label>
						<label v-else>
							<uni-icons type="left" size="15" color="#ccc"></uni-icons>
						</label>
						<label>
							我的素材
						</label>
						
					</view>
					<view class="timbre-title-close right" @click="closePopup()">
						<uni-icons type="closeempty" size="20" color="#999"></uni-icons>
					</view>
				</view>
				
				<!--内容开始-->
				<view class="mate-content left clearfix relative">
					<view class="mate-no-null left clearfix"  v-if="!folderList || !folderList[0]">
						<view>
							<uni-icons type="icon-wujilu17" color="#ddd" size="60" custom-prefix="iconfont"></uni-icons>
						</view>
						<view>
							 暂无记录
						</view>
					</view>
					
					<view class="mate-folder-item left clearfix relative" v-for="(item,index) in folderList" v-if="(!folerItem || !folerItem._id) && folderList">
						<view class="mate-folder-icon left" style="height:70px;line-height:70px;"  @click="getFileList(item,index)">
							<uni-icons type="icon-wenjianjia" size="60" color="#f3a73f" custom-prefix="iconfont"></uni-icons>
						</view>
						<view class="mate-folder-text left ellipsis"  @click="getFileList(item,index)">
							{{item.title}}
						</view>
						
						<view class="mate-more absolute" @mouseenter="showEdit(true,index,item)" @mouseleave="showEdit(false,index,item)">
							<uni-icons type="icon-gengduo2" color="#777" size="20" custom-prefix="iconfont"></uni-icons>
							<view class="mate-more-view absolute" v-if="showItem.index==index && showItem.show==true">
								<view>
									<uni-icons type="icon-chuangzuo2" @click="editFolder(item,index,'folder')" style="margin-right:10px;" color="#ddd" size="20" custom-prefix="iconfont"></uni-icons>
									<uni-icons @click="alertRemove(item,index,'folder')" type="icon-shanchu3" color="#ddd" size="20" custom-prefix="iconfont"></uni-icons>
								</view>
								
							</view>
							
						</view>
						
						
					</view>
					
					
					
					<!--文件列表-->
					<view class="mate-file-item left clearfix relative" v-for="(item,index) in fileList" v-if="folerItem && folerItem._id">
						<view class="mate-folder-icon left relative" style="height:60px;line-height:60px;margin-top:10px;"  @click="selectFile(item,index)">
							<image :src="item.poster" mode="aspectFit" style="width:100%;height:100%;" v-if="item.poster"></image>
							<zmt-colorful-ring v-else-if="!item.poster" text=" "  :width="40"></zmt-colorful-ring>
							<!--选中遮罩层-->
							<view class="mate-dui-box left clearfix absolute" v-if="selectedFile.findIndex(file => file._id === item._id)!= -1">
								<uni-icons type="icon-duigou3" size="15" color="#18bc37" custom-prefix="iconfont"></uni-icons>
							</view>
						</view>
						<view class="mate-folder-text left ellipsis" style="margin-top:5px;"  @click="getFileList(item,index)">
							{{item.title}}
						</view>
						
						<view class="mate-more absolute" style="top:-4px;" @mouseenter="showEdit(true,index,item)" @mouseleave="showEdit(false,index,item)">
							<uni-icons type="icon-gengduo2" color="#777" size="20" custom-prefix="iconfont"></uni-icons>
							<view class="mate-more-view absolute" v-if="showItem.index==index && showItem.show==true">
								<view>
									<uni-icons type="icon-chuangzuo2" @click="editFolder(item,index,'file')" style="margin-right:10px;" color="#ddd" size="20" custom-prefix="iconfont"></uni-icons>
									<uni-icons @click="alertRemove(item,index,'file')" type="icon-shanchu3" color="#ddd" size="20" custom-prefix="iconfont"></uni-icons>
								</view>
								
							</view>
							
						</view>
						
						
					</view>
					
					
					<!--新建文件夹-->
					<view class="mate-add-folder absolute" v-if="addFolder==true">
						<view class="mate-add-folder-input left clearfix">
							<input placeholder="请输入文件夹名称" maxlength="20" v-model="folderTitle" />
							
							<view class="mate-add-button right" @click="submitFolder()">
								确定
							</view>
							
						</view>
						
						<uni-icons type="closeempty" @click="closeAddFolder()" size="16" style="cursor:pointer;" color="#999"></uni-icons>
					</view>
					
				</view>
				<view class="mate-button left clearfix">
					<view class="mate-button-item right" v-if="folerItem && folerItem._id && !selectedFile[0]" @click="uploadFile()">
						<uni-icons type="icon-icon-" size="15" style="margin-right:3px;" color="#fff" custom-prefix="iconfont"></uni-icons>上传文件
					</view>
					
					<view class="mate-button-item right" v-if="folerItem && folerItem._id && selectedFile[0]" @click="submitSelectedFile()">
						({{selectedFile.length}})确定
					</view>
					
					<view class="mate-button-item right" @click="alertAddFolder()"  v-if="!folerItem || !folerItem._id">
						<uni-icons type="icon-wenjianjia" size="15" style="margin-right:3px;" color="#fff" custom-prefix="iconfont"></uni-icons>新建文件夹
					</view>
				</view>
			</view>
		</uni-popup>
		
		<up-modal :show="showRemove" @cancel="showRemove=false" @confirm="remove()" :showCancelButton="true" title="删除确认" content='确认要删除吗？'></up-modal>
	</view>
	
</template>

<style scoped>
	.mate-dui-box{width:30px;height:30px;line-height:30px;text-align:center;background:#fff;z-index:9999;right:0;bottom:-30px;border-radius: 5px;}
	.mate-title-left label{float:left;margin-right:5px;}
	.mate-file-item{width:100px;height:100px;box-shadow: 1px 2px 8px 0 rgb(0 0 0 / 10%);margin:10px;border-radius: 5px;cursor:pointer;}
	.mate-more-view view{float:left;line-height:30px;height:30px;margin-top:35px;text-align: center;width:100%;cursor:pointer;}
	.mate-more-view{width:100px;height:100px;background:rgba(0,0,0,.5);top:0;left:-77px;bottom:0;z-index:100;border-radius: 5px;}
	.mate-more{right:3px;top:2px;cursor:pointer;}
	.mate-folder-icon,.mate-folder-text{width:100%;text-align: center;line-height:20px;font-size:12px;color:#666;}
	.mate-folder-item{width:100px;height:100px;box-shadow: 1px 2px 8px 0 rgb(0 0 0 / 10%);margin:10px;border-radius: 5px;cursor:pointer;}
	.mate-add-button{width:70px;height:38px;line-height:38px;text-align: center;background:#2979ff;color:#fff;font-size:13px;margin-top:1px;margin-right:1px;cursor:pointer;border-radius: 2px;}
	.mate-add-folder-input input{float:left;width:calc(70% - 10px);line-height:40px;height:40px;padding-left:10px;font-size:14px;}
	.mate-add-folder-input{width:90%;margin-left:5%;margin-top:30px;border:1px solid #ddd;line-height:40px;height:40px;font-size:14px;border-radius: 3px;}
	.mate-add-folder{width:400px;height:100px;border:1px solid #eee;top:175px;left:calc((100% - 400px)/2);background:#fff;border-radius: 5px;box-shadow: 1px 2px 8px 0 rgb(0 0 0 / 10%);}
	.mate-no-null view{text-align: center;font-size:14px;color:#999;line-height:30px;}
	.mate-no-null{width:100px;height:80px;margin-left:calc((100% - 100px)/2);margin-top:185px;}
	.mate-button-item{padding-left:15px;padding-right:15px;line-height:35px;background:#2979ff;color:#fff;font-size:14px;border-radius: 5px;margin-left:20px;cursor:pointer;}
	.mate-button{width:96%;margin-left:2%;height:40px;margin-top:15px;}
	.mate-content{width:96%;margin-left:2%;height:450px;margin-top:20px;overflow: auto;}
	.timbre-title-close{width:30px;height:50px;line-height:50px;margin-right:5px;cursor:pointer;}
	.mate-title-left{line-height:50px;margin-left:20px;font-size:14px;}
	.mate-title-box{width:100%;height:50px;border-bottom:1px solid #eee;}
	.mate-box{width:1000px;height:600px;background:#fff;border-radius: 12px;}
</style>

<script>
	var db = uniCloud.database();
	import common from '@/static/js/common.js';
	var aliyun = uniCloud.importObject('aliyun',{customUI:true});
	export default {
		data() {
			return {
				folderTitle:'新建文件夹',
				folderList:[],
				addFolder:false,
				showItem:{},
				removeItem:{},//删除选项
				showRemove:false,
				folerItem:null,
				editItem:null,
				fileList:[],//文件夹列表
				percent:[],
				selectedFile:[]
			}
		},
		props:{
			show:{ //是否显示
				type:Boolean,
				default:false
			},
			userinfo:{ //登录用户信息
				type:Object
			},
			file:{
				type:Array
			}
		},
		watch:{
			"show"(val){
				if(val == true){
					var that = this;
					this.folerItem = null;
					that.selectedFile = that.file;
					this.$refs.popup.open();
				}else if(val == false){
					this.$refs.popup.close();
				}
			},
			"file"(val){
				this.selectedFile = val;
			}
		},
		mounted() {
			var that = this;
			this.getFolderList();
			
		},
		methods:{
			//确定选择素材以后
			submitSelectedFile(){
				this.$emit('selectedFile',this.selectedFile);
				this.closePopup();
			},
			//选择素材
			selectFile(item,index){
				var selectedFile = this.selectedFile;
				var index = selectedFile.findIndex(file => file._id === item._id);
				if(index!= -1){
					this.selectedFile.splice(index,1);
				}else{
					//最多选择20张
					if(selectedFile.length >= 20){
						uni.showToast({
							title:'最大选择数量为20',
							icon:'none'
						})
						
						return false;
					}
					
					this.selectedFile.push(item);
				}
				
			},
			//上传素材
			uploadFile(){
				var that = this;
				uni.chooseFile({
					count:20,
					sourceType: ['album'],
					extension:['png','jpg','jpeg','gif','webp','bmp','mp4','avi','wmv','mov'],
					success: function (res) {
						console.log('res',res);
						var tempFilePath = res.tempFilePaths;
						var tempFiles = res.tempFiles;
						for(var i = 0;i < tempFilePath.length;i ++){
							var tempFilePathUrl = tempFilePath[i];
							var fileType = that.checkFileFormat(tempFiles[i].name);
							var fileName = common.generateUUIDWithExtension(tempFiles[i].name);
							var title = tempFiles[i].name;
							that.fileList.unshift({
								poster:'',
								title:tempFiles[i].name,
								uuid:fileName
							});
							
							that.upload(tempFilePathUrl,fileName,title,fileType);
							
						}
						
					}
				});
			},
			//上传文件
			upload(tempFilePathUrl,fileName,title,fileType){
				var that = this;
				
				uniCloud.uploadFile({
				        filePath: tempFilePathUrl,
				        cloudPath: fileName,
				        success(e) {
							var fileID = e.fileID;
							//添加到数据库
							that.insertDataToDatabase(fileID,fileName,title,fileType);
						}
				      });
			},
			
			//插入数据库
			async insertDataToDatabase(fileID,fileName,title,fileType){
				var that = this;
				//获取视频的基本信息
				if(fileType == 'video'){
					var videoInfo = await that.getVideoInfo(fileID);
				}else if(fileType == 'image'){
					var videoInfo = await that.getImageInfo(fileID);
				}
				
				var data = {
					"duration": Math.ceil(videoInfo.duration),
					"width": videoInfo.width,
					"height": videoInfo.height,
					"size": videoInfo.size,
					"title": title,
					"url": fileID,
					"type": fileType,
					"uid": that.userinfo._id,
					"folder_id": that.folerItem._id
				}
				var uuidName = that.getFilenameWithoutExtension(fileName);
				db.collection('material').add(data).then(res=>{
					var index = that.fileList.findIndex(file => file.uuid === fileName);
					console.log('index',index);
					var id = res.result.id;
					data._id = id;
					console.log('type',fileType);
					if(fileType == 'video'){
						aliyun.getPosterFromVideo(fileID,id,uuidName).then(result=>{
							var poster = result.result.data.result;
							data.poster = poster;
							that.fileList[index] = data;
						});
					}else{
						db.collection('material').where({_id:id}).update({poster:fileID}).then(result=>{
							data.poster = fileID;
							that.fileList[index] = data;
						});
						
					}
					
				});
			},
			/**
			 * 从带后缀的文件名中提取文件名（不含后缀）
			 * @param {string} filename - 完整的文件名
			 * @returns {string} - 不含后缀的文件名
			 */
			getFilenameWithoutExtension(filename) {
			  if (!filename || typeof filename !== 'string') {
			    return '';
			  }
			
			  // 处理包含路径的文件名（提取最后一部分）
			  const baseName = filename.split(/[\\/]/).pop();
			  
			  // 处理包含多个点号的情况（如"example.min.js"）
			  const lastDotIndex = baseName.lastIndexOf('.');
			  
			  // 如果没有点号或点号在第一位（如隐藏文件".gitignore"），返回原文件名
			  if (lastDotIndex <= 0) {
			    return baseName;
			  }
			  
			  return baseName.substring(0, lastDotIndex);
			},
			//获取图片基本信息
			getImageInfo(src) {
			  return new Promise((resolve, reject) => {
			    uni.getImageInfo({
			      src,
			      success: resolve,
			      fail: reject
			    });
			  });
			},
			//获取视频基本信息
			getVideoInfo(src) {
			  return new Promise((resolve, reject) => {
			    uni.getVideoInfo({
			      src,
			      success: resolve,
			      fail: reject
			    });
			  });
			},
			//判断文件是图片还是视频
			checkFileFormat(fileName) {
			    const extension = this.getFileExtension(fileName);
			    const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
			    const videoExtensions = ['mp4', 'avi', 'mov', 'mkv', 'flv', 'wmv'];
			
			    if (imageExtensions.includes(extension)) {
			        return 'image';
			    } else if (videoExtensions.includes(extension)) {
			        return 'video';
			    }
			    return '未知格式';
			},
			//获取扩展名
			getFileExtension(fileName) {
			    const lastDotIndex = fileName.lastIndexOf('.');
			    if (lastDotIndex === -1) {
			        return '';
			    }
			    return fileName.slice(lastDotIndex + 1);
			},
			//弹出新建文件夹
			alertAddFolder(){
				console.log(3333);
				this.folerItem = null;
				this.editItem = null;
				this.folderTitle = '新建文件夹';
				this.addFolder = true;
			},
			//关闭修改标题弹窗
			closeAddFolder(){
				this.addFolder = false;
				this.title = '';
			},
			//获取文件列表
			getFileList(item,index){
				this.folerItem = item;
				var userinfo = this.userinfo;
				//查询出文件夹下的文件
				db.collection('material').where({folder_id:item._id,uid:userinfo._id}).orderBy('create_date desc').get().then(res=>{
					this.fileList = res.result.data;
				});
			},
			//关闭弹窗
			closePopup(){
				this.$refs.popup.close();
				this.$emit('close',false);
			},
			//弹出编辑标题弹窗
			editFolder(item,index,type){
				this.editItem = {
					item:item,
					index:index,
					type:type
				}
				this.addFolder = true;
				this.folderTitle = item.title;
			},
			//删除文件夹
			remove(){
				var item = this.removeItem;
				var id = item.item._id;
				var index = item.index;
				var type = item.type;
				if(id){
					if(type == 'folder'){
						db.collection('material_folder').where({_id:id}).remove().then(res=>{
							this.showRemove = false;
							uni.showToast({
								title:'删除成功',
								icon:'none',
								duration:2000
							})
							
							this.folderList.splice(index,1);
						});
					}else if(type == 'file'){
						db.collection('material').where({_id:id}).remove().then(res=>{
							this.showRemove = false;
							uni.showToast({
								title:'删除成功',
								icon:'none',
								duration:2000
							})
							
							this.fileList.splice(index,1);
						});
					}
					
				}
			},
			//弹出删除确认框
			alertRemove(item,index,type){
				//查询该目录下是否有文件
				var id = item._id;
				if(id){
					db.collection('material').where({folder_id:id}).get().then(res=>{
						var data = res.result.data;
						if(data.length > 0){
							uni.showToast({
								title:'该文件下有文件，请先删除文件',
								icon:'none'
							})
						}else{
							this.removeItem = {
								item:item,
								index:index,
								type:type
							}
							this.showRemove = true;
						}
					});
					
				}
				
			},
			//设置显示和隐藏修改
			showEdit(show,index,item){
				this.showItem = {
					show:show,
					index:index,
					item:item
				}
			},
			//获取文件夹列表
			getFolderList(){
				db.collection('material_folder').where({uid:this.userinfo._id}).orderBy('sort asc,create_date desc').get().then(res=>{
					this.folderList = res.result.data;
				});
			},
			//添加文件夹
			submitFolder(){
				var title = this.folderTitle;
				var userinfo = this.userinfo;
				if(this.editItem){
					var editItem = this.editItem;
					var id = editItem.item._id;
					var type = editItem.type;
				}
				
				if(!title){
					uni.showToast({
						title:'请输入文件夹名称',
						icon:'none',
						duration:2000
					})
					return false;
				}
				
				if(!userinfo || !userinfo._id){
					uni.showToast({
						title:'请先登录',
						icon:'none',
						duration:2000
					})
					return false;
				}
				
				var data = {
					title:title,
					uid:userinfo._id,
					sort:0,
					create_date:new Date().getTime()
				}
				
				if(!id){
					db.collection('material_folder').add(data).then(res=>{
						data._id = res.result.id;
						if(res.success == true){
							uni.showToast({
								title:'添加成功',
								icon:'none',
								duration:2000
							})
						}
						
						this.folderList.unshift(data);
						this.addFolder = false;
						
					});
				}else if(id.length > 5){
					if(type == 'folder'){
						db.collection('material_folder').where({_id:id}).update({title:title}).then(res=>{
							data._id = id;
							uni.showToast({
								title:'修改成功',
								icon:'none',
								duration:2000
							})
							this.folderList[editItem.index] = data;
							this.addFolder = false;
						});
					}else if(type == 'file'){
						db.collection('material').where({_id:id}).update({title:title}).then(res=>{
							data._id = id;
							uni.showToast({
								title:'修改成功',
								icon:'none',
								duration:2000
							})
							this.fileList[editItem.index].title = title;
							this.addFolder = false;
						});
					}
					
				}
				
				
			}
		}
	}
</script>

